import { RouteRecordRaw } from "vue-router";
import { Module } from "vuex";
import { Store } from "../../../typings/store";
import { ROUTES } from "../../constant";
import { authRoutes } from "../../router/modules/authRoutes";
import { publicRoutes } from "../../router/modules/publicRoutes";
import { getFilterRoutes } from "../../utils/router";
import { sessionGetItem } from "../../utils/storage";
const permission:Module<Store.Permission<{}>,any> = {
  namespaced: true,
  state: {
    // 路由表：初始拥有静态路由权限
    routes: publicRoutes,
    menus: sessionGetItem(ROUTES) || [],
  },
  mutations: {
    /**
     * 增加路由
     */
    setRoutes (state, newRoutes:[]) {
        // 永远在静态路由的基础上增加新路由
        state.routes = [...publicRoutes, ...newRoutes]
    }
  },
  actions: {
    /**
     * 根据权限筛选路由
     */
    filterRoutes ({commit}, menus:Store.Menus[]) {
        const filterRoutes = getFilterRoutes(authRoutes as RouteRecordRaw[], menus);
        // 最后添加 不匹配路由进入 error
        filterRoutes.push({
          path: '/:catchAll(.*)',
          redirect: '/error'
        })
        commit('setRoutes', filterRoutes)
        return filterRoutes;
      }
  },
};

export default permission;